package 刷题.leedcode11;
//链表分割
public class Partition1 {
    public ListNode partition(ListNode pHead,int x){
        //新建两个链表
        //一个用来存储小于x的结点，一个用来存储大于x的结点并保存头结点
        //最后让第一条链表的next=第二条链表的head
        ListNode preHead = new ListNode(0);
        ListNode curHead = new ListNode(0);
        ListNode prev = preHead;
        ListNode cur = curHead;
        while(pHead != null){
            if(pHead.val < x){
                preHead.next = pHead;
                preHead = preHead.next;
            }else{
                curHead.next = pHead;
                curHead = curHead.next;
            }
            pHead = pHead.next;
        }
        prev = prev.next;
        cur = cur.next;
        //连接两个链表
        preHead.next = cur;
        //cur不为空，让curHead的尾结点为空
        if(cur != null){
            curHead.next = null;
        }
        if(prev == null){
            return cur;
        }
        return prev;
    }
}
